<?php
namespace app\common\model;
class Tasking extends Base{
    function source(){
    	return $this->belongsTo('source');
    }
    function media(){
    	return $this->belongsToMany('media','task_media','media_id','task_id');
    }
    function device(){
        return $this->belongsToMany('device','task_device','device_id','task_id');
    }
    /**
     * 将任务加入任务执行器队列 或者 进行任务定时
     * @param  array||integer $id 任务ID || 通过 $this->getTask()获取到的任务
     * @return array
     */
    function runTask($id,$isExecute=false){
        $task=[];
        if(is_array($id)){
            $task=$id;
        }else{
            $has=$this->getTask(['id'=>$id],0,['toArray'=>true]);
            if(!empty($has)&&isset($has[0])){
                $task=$has[0];
            }else{

            }
        }
        if(empty($task)){
            return error('该任务不存在');
        }
        if($task['loop']&&!$isExecute){ //循环任务定时
            return \socket\Socket::timing($task,$task['member_id']);
        }elseif($task['start_time']>time()&&!$isExecute){ // 正常任务定时
            return \socket\Socket::timing($task,$task['member_id']);
        }else{ // 已到执行时间 则立即加入执行队列
            // 加入队列 通知后台(任务管理器)更新列表
            $rs=$this->pushTask($task);
            if($rs['success']){
                model('task_device')->updateDev($task['member_id'],$task);
            }
            return $rs;
        }

    }
    /**
     * 将新任务加入执行队列  tasking => task_device
     * @param  integer||array $id 任务ID || $this->getTask返回的任务数据
     * @return array
     */
    function pushTask($id,$dev_id=0){
        $task=[];
        if(is_array($id)){
            $task=$id;
        }else{
            $has=$this->getTask(['id'=>$id],0,['toArray'=>true]);
            if(!empty($has)&&isset($has[0])){
                $task=$has[0];
            }
        }
        if(empty($task)){
            return error('该任务不存在');
        }
        $task_id=$task['id'];
        // 该任务正在队列中(避免多次分配)
        $queueMap=['task_id'=>$task_id];
        if($dev_id>0){
            $queueMap['device_id']=$dev_id;
        }
        $hasQueue=model('task_device')->where($queueMap)->count();
        if($hasQueue>0){
            // 此处可以进行 查询是否 已经加入所有的设备队列（略）
            return success('该任务已在队列中');
        }
        $device=$task['device'];
        $member_id=$task['member_id'];
        if($dev_id>0){
            $device=[$dev_id];
        }else{
            if(is_string($device)){
                $device=json_decode($device,true);
            }
            if(empty($device)){
                $device=model('device')->getDevice($member_id,1);
            }
        }
        if(empty($device)){
            return error('请先为该用户添加设备');
        }
        if(is_string($device)){
           $device=json_decode($device,true); 
        }
        $data=[];
        $time=time();
        foreach($device as $v){
            array_push($data,[
                'member_id'=>$member_id,
                'task_id'=>$task_id,
                'device_id'=>$v,
                'sort'=>$time,
            ]);

        }
        $add=model('task_device')->add($data);
        if($add){
            $this->edit(['id'=>$task_id,'status'=>1]);
            // 获取当前悠闲设备 发布任务指令
            $devs=model('device')->getDevice($member_id,1,true);
            $qModel=model('task_device');
            foreach($devs as $v){
                $qModel->nextTask($member_id,$v);
            }
            return success();
        }
        return error();
    }
    /**
     * 获取完整的任务信息（包含多媒体、素材等详细的资料）
     * @param  array   $where  [description]
     * @param  integer $page   [description]
     * @param  array   $option [description]
     * @return [type]          [description]
     */
    function getTask($where=[],$page=0,$option=[]){
        $field=isset($option['field'])?$option['field']:"*";
        $with=isset($option['with'])?$option['with']:[];
    	$with=array_merge($with,['media','source','source.media']);
        $order=isset($option['order'])?$option['order']:'';
        $options=[
            'field'=>$field,
            'with'=>$with,
            'order'=>$order,
        ];
    	$list=$this->readAll($where,$page,$options);
        if(isset($option['toArray'])&&count($list)){
            $list=$list->toArray(); 
            $list=isset($list['data'])?$list['data']:$list; 
        }
        foreach($list as $k => $v){
        	if(!empty($v['source'])){
                if(!$v['msg'])$v['msg']=$v['source']['msg'];
                if(count($v['source']['media'])&&!count($v['media'])){
        			$v['media']=$v['source']['media'];
        		}
        		unset($v['source']);
        	}
            foreach ($v['media'] as $i=> $c) {
                $c['src']=images($c['link']);
                $v['media'][$i]=$c;
            }
            if(is_string($v['software'])){
                $v['software']=json_decode($v['software'],true);
            } 
            if(is_array($v['software'])){
                $v['software']=array_unique($v['software']);
            }
            if(is_string($v['social'])){
                $v['social']=json_decode($v['social'],true);
            }
            if(is_array($v['social'])){
                $v['social']=array_unique($v['social']);
            }

            $list[$k]=$v;
        }
    	return $list;
    }
    
}
